import { fileUrl } from '../../api/config.js';

/**
 * 附件上传，调用moa原生方法
 * @param {Object} param
    param.src 图片本地路径数据
    param.bizId 业务id
    param.bizType 业务类型
    param.fileGroup 业务分组
    param.accessToken
 * 使用
 * fileUploadByRay(param).then((res) => {
        if (res === true) {
            // 上传成功
        }
     },
     (err) => {
        if (err === false) {
            // 上传失败
      }
    });
 */
export default function(param, showLoading) {
    let p = new Promise((resolve, reject) => {
        // 处理附件上传的参数
        let src = param.src,
            formData = {},
            file = [];
        formData.bizId = param.bizId;
        formData.bizType = param.bizType;
        formData.fileGroup = param.fileGroup;
        formData.accessToken = param.accessToken;
        src.forEach((item) => {
            file.push({
                filePath: decodeURI(item),
                fileKey: 'partFile'
            })
        });
        if (showLoading) {
            uni.showLoading({
                title: '上传附件中...'
            });
        }
        // 链动附件上传方法
        app.file.uploadFiles({
            url: fileUrl + '/upload',
            files: file,
            header: {
                'accessToken': param.accessToken
            },
            formData: formData, // http请求中其他额外的form data
            callback: (res) => {
                console.log(res);
                let resp = null;
                if (showLoading) {
                    uni.hideLoading();
                }
                if (typeof(res) == 'object' && res) {
                    resp = res;
                } else {
                    resp = JSON.parse(res);
                }
                if ((resp.status == undefined && resp.status != -1) && resp.code == 200 && resp.state) {
                    // 上传完成
                    resolve(true);
                } else {
                    reject(false);
                }
            }
        })
    });
    return p;
}
